package dao

import (
	"go-weixin/app/usercenter/model"
	"go-weixin/common/chendb"
	// "go-weixin/common/utils"
)

type RoleDao struct {
	engine chendb.ChenDb
}

func NewRoleDao(engine chendb.ChenDb) *RoleDao {
	return &RoleDao{
		engine: engine,
	}
}
func (u RoleDao) RoleAdd(name string, weight int64, parentId int64, role *model.RoleModel) (int64, error) {
	role.Name = name
	role.Weight = weight
	role.ParentId = parentId
	return u.engine.Insert(role)
}

func (u RoleDao) RoleExistByName(name string) (bool, error) {
	return u.engine.Exist(&model.RoleModel{
		Name: name,
	})
}

func (u RoleDao) RoleUpdateExisByName(name string, id int64) (bool, error) {
	return u.engine.Where("name = ? AND id != ?", name, id).Exist(&model.RoleModel{})
}
func (u RoleDao) RoleUpdate(id int64, role *model.RoleModel) (int64, error) {
	return u.engine.ID(id).Update(role)
}
func (u RoleDao) RoleGet(id int64, role *model.RoleModel) (bool, error) {
	return u.engine.ID(id).Get(role)
}

func (u RoleDao) RoleExistById(id int64) (bool, error) {
	return u.engine.Exist(&model.RoleModel{
		Id: id,
	})
}

func (u RoleDao) RoleAddPowerExist(roleId int64, powerId int64) (bool, error) {
	return u.engine.Exist(&model.RolePowerModel{
		RoleId:  roleId,
		PowerId: powerId,
	})
}

func (u RoleDao) RoleAddPower(roleId int64, powerId int64) (int64, error) {
	return u.engine.Insert(&model.RolePowerModel{
		RoleId:  roleId,
		PowerId: powerId,
	})
}
func (u RoleDao) RoleUpdatePowerExiste(roleId int64, newPowerId int64) (bool, error) {
	return u.engine.Exist(&model.RolePowerModel{
		RoleId:  roleId,
		PowerId: newPowerId,
	})
}
func (u RoleDao) RoleUpdatePower(roleId int64, oldPowerId int64, newPowerId int64) (int64, error) {
	return u.engine.Where("role_id = ? AND power_id = ?", roleId, oldPowerId).Update(&model.RolePowerModel{
		PowerId: newPowerId,
	})
}

func (u RoleDao) RoleList(limit int64, offset int64, roleList *[]model.RoleModel) error {
	return u.engine.Limit(int(limit), int(offset)).Find(roleList)
}

func (u RoleDao) GetRoleById(id int64, role *model.RoleModel) (bool, error) {
	return u.engine.ID(id).Get(role)
}

func (u RoleDao) RoleGetPowerById(id int64, powerList *[]model.PowerModel) error {
	rp := new(model.RolePowerModel)
	p := new(model.PowerModel)
	return u.engine.Table(rp.TableName()).Alias("rp").
		Join("INNER", []string{p.TableName(), "p"}, "rp.power_id = p.id").
		Where("rp.role_id = ?", id).
		Select("p.*").
		Find(powerList)
}

func (u RoleDao) RoleGetUserById(id int64, userList *[]model.UserModel) error {
	ur := new(model.UserRoleModel)
	us := new(model.UserModel)
	return u.engine.Table(ur.TableName()).Alias("ur").
		Join("INNER", []string{us.TableName(), "u"}, "ur.user_id = u.id").
		Where("ur.role_id = ?", id).
		Select("u.*").
		Find(userList)
}
